<template>
	<view class="chat">
		<!-- 导航栏 -->
		<navTitle :titleRight="''" :title="'消息'"></navTitle>

		<!-- 聊天消息显示区域 -->
		<scroll-view :style="{height: `${windowHeight - inputHeight - 200}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view">

			<view id="msglistview" class="chat-body">
				<view class="job_box" v-if="job.company_scale_id">
					<view class="job_li">
						<view class="l-title">
							<view>{{ job.job_name }}</view>
							<view class="l-t-r">{{ job.salary_text }}</view>
						</view>
						<view class="l-name">
							<span>{{ job.full_name }}</span>
							<span>{{getCompanyScaleName(job.company_scale_id) }}</span>
						</view>
						<view class="l-desc">
							<view>{{ job.responsibility }}</view>
						</view>
					</view>
				</view>
				<!-- 用户发送的消息，简历文件和图片消息都显示在右侧 -->
				<view v-for="(item, index) in msgList" :key="index">
					<!-- 用户消息 -->
					<view class="item self"
						v-if="item.content !== '' || item.infotype === 'file' || item.infotype === 'img'">
						<view class="content right">
							<!-- 文件类型 -->
							<span v-if="item.infotype === 'file'">
								<a href="javascript:void(0);" @click="previewFile(item.data, $event)">
									{{ item.content }}
								</a>
							</span>

							<!-- 图片类型 -->
							<img v-if="item.infotype === 'img'" :src="item.data" class="message-image"
								@click="previewImage(item.data)" />

							<!-- 文本消息 -->
							<span v-if="item.infotype === 'txt'">{{ item.content }}</span>
						</view>
						<image class="avatar" :src="item.avatar" />
					</view>

					<!-- 机器人消息 -->
					<view class="item Ai" v-if="item.botContent !== ''">
						<image class="avatar" :src="item.avatar" />
						<view class="content left">
							<!-- 机器人发送文件 -->
							<span v-if="item.infotype === 'file'">
								<a href="javascript:void(0);" @click="previewFile(item.data, $event)">
									{{ item.filename }}
								</a>
							</span>

							<!-- 机器人发送图片 -->
							<img v-if="item.infotype === 'img'" :src="item.data" class="message-image"
								@click="previewImage(item.data)" />

							<!-- 其他内容 -->
							<span v-if="item.infotype === 'txt'" v-html="item.content"></span>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部消息发送栏 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
				<!-- 发简历按钮 -->
				<button @click="selectResume" class="send-btn resume-btn">发简历</button>

				<!-- 输入框 -->
				<view class="uni-textarea">
					<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
						placeholder="快来聊天吧~" :show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight"
						@focus="focus" @blur="blur" auto-height></textarea>
				</view>

				<!-- 表情按钮 -->
				<!-- 	<view class="send-btn xiao">
					<img src="/static/images/tabbar/iconxiao.png" alt="" />
				</view> -->

				<!-- 选择图片按钮 -->
				<view class="send-btn photo" @click="selectImage">
					<u-icon name="photo" size="38"></u-icon>
				</view>
			</view>
		</view>

		<!-- 简历弹出框 -->
		<view v-if="isResumePopupVisible" class="resume-popup">
			<view class="popup-header">
				<text>选择简历</text>
				<u-icon name="close" size="30" @click="closeResumePopup" />
			</view>
			<view class="resume-list">
				<view v-for="(resume, index) in resumes" :key="index" class="resume-item" @click="sendResume(resume)">
					<image src="/static/images/user/icon_u_jl.png" alt="" class="resume-avatar" />
					<text class="resume-text">{{ resume.file }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// import * as pdfjsLib from 'pdfjs-dist';
	import {
		resumeFileList,
		getmyPriatexinxi
	} from '../../utils/api';
	import navTitle from './../boss/components/nav-title.vue';
	export default {
		components: {
			navTitle
		},
		data() {
			return {
				job: {},
				fromuid: '',
				keyboardHeight: 0, // 键盘高度
				bottomHeight: 0, // 底部消息发送栏高度
				scrollTop: 0, // 滚动距离
				userId: '', // 当前用户ID
				chatMsg: "", // 发送的消息
				msgList: [],
				socketOpen: false, // WebSocket 是否已连接
				socketTask: null, // WebSocket 实例
				username: '匿名', // 当前用户名
				isResumePopupVisible: false, // 控制简历弹窗的显示
				resumes: [], // 存储简历数据
			};
		},
		updated() {
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
			},
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight;
			}
		},
		onLoad(option) {
			console.log(option, 'ppoop')
			this.job = option
			console.log(this.job, 'ppoop')
			this.fromuid = option.fromuid
			this.mesDetaileList()
			this.initWebSocket();
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = this.rpxTopx(res.height);
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			});
		},
		mounted() {
			this.userId = uni.getStorageSync('userInfo').id
			console.log(this.userId, 'wode')
		},
		onShow() {
			
		},
		methods: {
			// 显示简历弹窗
			selectResume() {
				this.isResumePopupVisible = true;
				this.fetchResumes(); // 请求简历接口
			},
			async mesDetaileList() {
				let res = await getmyPriatexinxi({
					fromuid: this.fromuid
				})
				console.log(res, 'RESthis.msgList')
				this.msgList = res.data
				console.log(this.msgList, 'this.msgList')
			},

			// 关闭简历弹窗
			closeResumePopup() {
				this.isResumePopupVisible = false;
			},
			previewFile(fileUrl, event) {
				// 阻止默认行为，防止页面跳转
				event.preventDefault();

				// 判断文件类型（比如 PDF）
				if (fileUrl.endsWith('.pdf')) {
					this.previewPDF(fileUrl);
				} else if (fileUrl.endsWith('.jpg') || fileUrl.endsWith('.png')) {
					this.previewImage(fileUrl); // 预览图片
				} else {
					console.log("其他文件类型", fileUrl);
				}
			},
			// 预览 PDF 文件
			previewPDF(fileUrl) {
				// 打开 WebView 来预览 PDF 文件
				uni.navigateTo({
					url: `/pages/job/webview?fileUrl=${encodeURIComponent(fileUrl)}`
				});
			},

			previewImage(imageUrl) {
				uni.previewImage({
					current: imageUrl, // 当前显示图片的链接
					urls: [imageUrl], // 要预览的图片链接数组
				});
			},
			async fetchResumes() {
				let res = await resumeFileList()
				this.resumes = res.data
				console.log(this.resumes, 'dsasd')
			},
			previewImages(content) {
				const imageRegex = /<img src="(data:image\/[^;]+;base64[^"]+)"/; // 正则匹配Base64图片
				const match = content.match(imageRegex);

				if (match && match[1]) {
					uni.previewImage({
						current: match[1], // 当前显示的图片路径
						urls: [match[1]], // 预览的图片列表
					});
				}
			},
			// 初始化 WebSocket 连接
			initWebSocket() {
				const url = 'wss://www.hkeh.cc/wss'; // 替换为实际的 WebSocket 地址

				// 使用 uni.connectSocket 建立 WebSocket 连接
				this.socketTask = uni.connectSocket({
					url: url,
					success: () => {
						console.log('WebSocket 连接成功');
						this.socketOpen = true; // 更新连接状态
					},
					fail: (error) => {
						console.error('WebSocket 连接失败:', error);
						this.socketOpen = false; // 设置连接状态为失败
					}
				});

				// WebSocket 连接成功打开时触发
				this.socketTask.onOpen(() => {
					console.log('WebSocket 连接已打开');
					// 监听 WebSocket 消息事件
					this.socketTask.onMessage((res) => {
						console.log('WebSocket 接收到消息:', res);

						try {
							// 尝试将接收到的消息解析为 JSON 格式
							const message = JSON.parse(res.data);

							// 如果消息类型是 'ping'，回复 'pong'
							if (message.type === 'ping') {
								this.socketTask.send({
									data: JSON.stringify({
										type: 'pong' // 回复的消息内容
									}),
								});
							}

							// 处理接收到的消息
							this.handleMessage(message);

						} catch (e) {
							console.error('解析 WebSocket 消息失败:', e, '原始数据:', res.data);
						}
					});

				});

				// 监听 WebSocket 连接关闭事件
				this.socketTask.onClose(() => {
					this.socketOpen = false; // 设置连接状态为关闭
					console.log('WebSocket 连接关闭');
				});

				// 监听 WebSocket 错误事件
				this.socketTask.onError((error) => {
					console.error('WebSocket 错误:', error);
				});
			},



			goback() {
				uni.switchTab({
					url: "/pages/tutorship/tutorship"
				});
			},

			focus() {
				this.scrollToBottom();
			},

			blur() {
				this.scrollToBottom();
			},

			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth;
				let rpx = (750 / deviceWidth) * Number(px);
				return Math.floor(rpx);
			},

			sendHeight() {
				setTimeout(() => {
					this.$nextTick(() => {
						let query = uni.createSelectorQuery().in(this);
						query.select('#scrollview').boundingClientRect();
						query.select('#msglistview').boundingClientRect();
						query.exec((res) => {
							if (res[1] && res[0] && res[1].height > res[0].height) {
								this.scrollTop = this.rpxTopx(res[1].height - res[0].height);
							}
						});
					});
				}, 10);
			},

			scrollToBottom() {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height);
						}
					});
				}, 15);
			},

			handleMessage(message) {
				const {
					type,
					infotype,
					data,
					uid,
					touid,
					filename
				} = message;
				let newMessage = {};

				// 处理消息类型
				if (type === "Private") {
					if (infotype === 'txt') {
						// 纯文本消息
						newMessage = {
							botContent: data,
							content: "",
							image: "/static/images/user/icon_u_jl.png"
						};
					} else if (infotype === 'img') {
						// 图片消息
						newMessage = {
							botContent: `<img src="${data}" alt="${filename}" class="message-image" style="max-width: 200rpx; max-height: 150rpx; object-fit: contain; border-radius: 10rpx;" />`,
							content: "",
							image: "/static/images/user/icon_u_jl.png"
						};
					} else if (infotype === 'file') {
						// 文件类型消息
						newMessage = {
							botContent: `收到一个文件: ${filename}`,
							content: "",
							image: "/static/images/user/icon_u_jl.png"
						};
					} else {
						// 其他类型消息
						newMessage = {
							botContent: `收到一个类型为 ${infotype} 的消息`,
							content: "",
							image: "/static/images/user/icon_u_jl.png"
						};
					}
					this.msgList.push(newMessage);
				} else if (type === "System") {
					// 处理系统消息
					this.msgList.push({
						botContent: `系统消息: ${data}`,
						content: "",
						image: "/static/images/user/icon_u_system.png"
					});
				} else if (type === "Infoerror") {
					// 处理敏感消息
					this.msgList.push({
						botContent: `敏感消息: ${data}`,
						content: "",
						image: "/static/images/user/icon_u_warning.png"
					});
				}

				// 滚动到最新消息
				this.scrollToBottom();
			},
			// 发送消息到 WebSocket 服务器
			handleSend() {
				console.log(this.userId, 'kkkkk')
				if (this.chatMsg && !/^\s+$/.test(this.chatMsg)) {
					const message = {
						type: "Private", // 私有消息
						uid: this.userId, // 当前用户ID
						touid: this.fromuid, // 收消息的用户ID
						from_group_id: 1, // 发送者组别
						to_group_id: 0, // 接收者组别
						infotype: "txt", // 消息类型为文本
						data: this.chatMsg // 发送的消息内容
					};

					this.msgList.push({
						botContent: "",
						content: this.chatMsg,
						infotype: "txt",
						image: "/static/images/user/icon_u_avater_default.png",
					});

					this.sendMessageToServer(message);
					this.chatMsg = '';
					this.scrollToBottom();
				} else {
					uni.showToast({
						icon: 'none',
						title: '不能发送空白消息'
					});
				}
			},

			sendResume(resume) {
				console.log(resume, 'pp')
				const message = {
					type: "Private",
					uid: this.userId,
					touid: this.fromuid,
					from_group_id: 0,
					to_group_id: 1,
					infotype: "file", // 文件类型
					data: resume.file, // 简历文件的URL或内容
					filename: resume.file
				};
				console.log(message, 'pp')
				// 将简历消息加入聊天记录
				this.msgList.push({
					botContent: "",
					content: `个人简历: ${resume.file}`,
					image: "/static/images/user/icon_u_avater_default.png",
					infotype: "file",
					data: resume.file, // 保存文件 URL
					// filename: resume.file  // 保存文件名
				});
				console.log(this.msgList, 'pssp')
				// 发送消息到服务器
				this.sendMessageToServer(message);

				// 发送后关闭弹窗
				this.closeResumePopup();
			},

			getCompanyScaleName(scaleId) {
				const scaleNames = {
					1: "20人以下",
					2: "20-99人",
					3: "100-499人",
					4: "500-999人",
					5: "1000-9999人",
					6: "10000人以上",
				};
				return scaleNames[scaleId] || '未知规模'; // 如果没有找到对应的规模，返回 '未知规模'
			},
			selectImage() {
				uni.chooseImage({
					count: 1, // 限制选择的图片数量
					success: (res) => {
						const file = res.tempFiles[0];
						this.handleImageChange(file);
					},
					fail: (error) => {
						console.error('图片选择失败:', error);
					}
				});
			},

			// 处理图片选择
			handleImageChange(file) {
				if (file) {
					const reader = new FileReader();
					reader.onload = (e) => {
						const message = {
							type: "Private",
							uid: this.userId,
							touid: this.fromuid,
							infotype: "img", // 消息类型为图片
							data: e.target.result, // 图片内容（base64 编码）
							filename: file.name
						};
						this.msgList.push({
							botContent: "",
							content: "发送图片: " + file.name,
							image: "/static/images/user/icon_u_avater_default.png",
							infotype: "img", // 标明消息类型为图片
							data: e.target.result // 图片的 base64 内容
						});
						this.sendMessageToServer(message);
					};
					reader.readAsDataURL(file); // 读取文件内容为 base64 格式
				}
			},


			sendMessageToServer(message) {
				console.log("发送消息：", message);

				if (this.socketTask && this.socketTask.send) {
					this.socketTask.send({
						data: JSON.stringify(message),
						success: () => {
							console.log('消息发送成功');
						},
						fail: (err) => {
							console.error('发送消息失败', err);
						}
					});
				} else {
					console.error('WebSocket 未连接或发送失败');
				}
			}
		}
	};
</script>



<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.resume-btn {
		width: 170rpx !important;
		background-color: #1c7af7; // 设置发送简历按钮的背景颜色
	}

	/* 聊天消息 */
	.chat {
		.topTabbar {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			display: flex;
			margin-top: 80rpx;
			justify-content: space-between;

			.icon {
				margin-left: 20rpx;
			}

			.text {
				margin: auto;
				font-size: 16px;
				font-weight: 700;
			}
		}

		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						// background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;

						image {
							align-self: center;
						}
					}
				}
			}
		}

		/* 简历弹窗样式 */
		.resume-popup {
			overflow-y: auto;
			overflow-x: hidden;
			/* 水平方向不显示滚动条 */
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			// background: rgba(0, 0, 0, 0.5);
			background-color: #FFFFFF;
			padding: 40rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			z-index: 999;
			height: 500rpx;
		}

		.popup-header {
			display: flex;
			justify-content: space-between;
			width: 100%;
			padding-bottom: 20rpx;
			color: black;
			font-size: 32rpx;
			font-weight: bold;
		}

		.resume-list {
			.resume-item {
				display: flex;
				align-items: center;
				padding: 20rpx;
				margin-bottom: 10rpx;
				background-color: #f9f9f9;
				border-radius: 8rpx;
				box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
			}

			.resume-avatar {
				width: 5%; // 头像占 20%
				height: 60rpx; // 可以根据实际需要调整高度
				// border-radius: 50%;
				margin-right: 10rpx;
				margin-left: 20%;
			}

			.resume-text {
				width: 50%; // 文字占 80%
				white-space: nowrap; // 禁止换行
				overflow: hidden; // 超出部分隐藏
				text-overflow: ellipsis; // 超出部分显示省略号
				font-size: 28rpx;
				color: #333;
			}
		}

		.resume-item:hover {
			background-color: #f0f0f0;
		}

		.resume-btn {
			width: 170rpx !important;
			background-color: #1c7af7;
		}

		::v-deep .message-image {
			max-width: 300rpx;
			/* 设置最大宽度 */
			max-height: 200rpx;
			/* 设置最大高度 */
			object-fit: contain;
			/* 保持比例，充满区域 */
			border-radius: 10rpx;
			/* 圆角效果 */
			cursor: pointer;
			/* 设置鼠标样式为点击状态 */
		}

		.send-btn.image-btn {
			// background-color: #FFB6C1;
			/* 设置发送图片按钮的颜色 */
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 15rpx 5rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 400rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 10rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
					text-indent: 30rpx;
					margin-left: 10rpx;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 73rpx;
				margin-left: 25rpx;
				width: 120rpx;
				height: 75rpx;
				background: #1c7af7;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}

			.photo {
				background-color: #FFFFFF;
			}

			.xiao {
				background-color: #FFFFFF;

				img {
					width: 60rpx;
					height: 60rpx;
				}
			}
		}
	}

	.job_box {
		width: calc(100% - 20px);
		margin: 0 auto;
	}

	.job_li {
		padding: 10px 20px;
		border-radius: 10px;
		background: #fff;
		font-size: 13px;
		color: #999999;
		line-height: 18px;
		margin: 10px auto 0;
	}

	.l-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-family: LucidaGrande, LucidaGrande;
		font-weight: bold;
		font-size: 16px;
		color: #333333;
		line-height: 18px;
	}

	.l-t-r {
		font-weight: 600;
		font-size: 16px;
		color: #1C7AF7;
		line-height: 22px;
	}

	.l-name {
		margin: 10px 0;
		font-size: 14px;
		color: #666666;
		line-height: 20px;

		span:last-child {
			margin-left: 10px;
		}
	}

	.l-desc {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		max-height: 40px;
		line-height: 18px;
	}
</style>